package org.springblade.oa.controller;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFFont;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springblade.core.secure.BladeUser;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.constant.SystemConstant;
import org.springblade.core.tool.utils.Func;
import org.springblade.oa.entity.InvoiceImage;
import org.springblade.oa.entity.Welfare;
import org.springblade.oa.service.IInvoiceImageService;
import org.springblade.oa.service.IWelfareService;
import org.springblade.oa.tool.ImageUtil;
import org.springblade.oa.tool.ZipUtils;
import org.springblade.oa.vo.InvoiceImageVo;
import org.springblade.oa.wrappper.InvoiceImageWrapper;
import org.springblade.system.feign.IDictClient;
import org.springblade.system.user.feign.IUserClient;
import org.springframework.core.io.ClassPathResource;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 福利费管理
 */
@RestController
@RequestMapping("/welfare")
@AllArgsConstructor
public class WelfareController {

	private IWelfareService iWelfareService;
	private IInvoiceImageService imageService;
	private IUserClient userClient;
	private IDictClient dictClient;

	/**
	 * 新增福利费
	 */
	@PostMapping("/insertWelfare")
	@ApiOperation(value = "新增福利非管理", notes = "传参welfare")
	public R insertWelfare(@RequestParam("files") MultipartFile[] files, InvoiceImage invoiceImage, Welfare welfare) {
		try {
			iWelfareService.saveOrUpdate( welfare );
			invoiceImage.setBxId( String.valueOf( welfare.getId() ) );
			invoiceImage.setModelType("2");
			imageService.saveBatch( files, invoiceImage );
			return R.status( true );
		} catch (Exception e) {
			return R.status( false );
		}
	}

	/**
	 * 福利费列表
	 */
	@PostMapping("/welfareList")
	@ApiOperation(value = "福利费列表", notes = "map")
	public R welfareList(@RequestBody Map<String, Object> map, BladeUser user) {
		String type = map.get( "type" ).toString();//判断是否是角色还是管理员
		String time = map.get( "time" ).toString();
		String fyType = map.get( "fyType" ).toString();
		Integer page = Integer.valueOf( map.get( "page" ).toString() );
		Integer pageSize = Integer.valueOf( map.get( "pageSize" ).toString() );

		Map<String, Object> rmap = new HashMap<>();

		Map<String, Object> params = new HashMap<>();
		//时间格式化
		List<String> tmes = new ArrayList<>();//时间范围
		String stime = "", etime = "";//起止时间
		if (time != null && !"".equals( time )) {
			time = time.replace( "，", "," );
			if (time.contains( "," )) {
				String[] times = time.split( "," );
				stime = times[0];
				etime = times[1];
			}
		}
		params.put( "startTime", stime );
		params.put( "endTime", etime );
		params.put( "fyType", fyType );

		if ("0".equals( type )) {
			params.put( "userId", user.getUserId() );
		} else {
			params.put( "userId", "" );
			params.put( "bmid", map.get( "bmid" ) == null ? "" : map.get( "bmid" ).toString() );
			params.put( "xm", map.get( "xm" ) == null ? "" : map.get( "xm" ).toString() );
		}
		params.put( "limit", getLimitStr( pageSize, page ));
		try {
		/*	QueryWrapper<Welfare> queryWrapper = new QueryWrapper<>();
			if (!"".equals( fyType )) {
				queryWrapper.eq( "fy_type", fyType );
			}
			if (!"".equals( stime )) {
				queryWrapper.apply( "date_format(fy_date,'%Y-%m') >= {0}", stime ).apply( "date_format(fy_date,'%Y-%m') <= {0}", etime );
			}
			if("0".equals( type )){
				queryWrapper.eq( "create_user", user.getUserId() );
			}*/
			List<Map<String, Object>> list = iWelfareService.getWelfareList( params );
			Integer total = iWelfareService.getWelfareListCount( params );
			String welfareCount = iWelfareService.getWelfareCount(params);

			rmap.put( "sumAmount", welfareCount );
			rmap.put( "data", list );
			rmap.put( "total", total );
		} catch (Exception e) {
			e.printStackTrace();
			return R.data( 200, rmap, "exception:" + e.getMessage() );
		}
		return R.data( rmap );
	}

	/**
	 * 获取福利标准
	 *
	 * @param user
	 * @return
	 */
	@GetMapping("/selectStandard")
	@ApiOperation(value = "获取福利标准", notes = "传参BladeUser")
	public R selectStandard(BladeUser user) {
		Integer standard = iWelfareService.selectStandardByRoleId( user.getRoleId() );
		if (standard != null) {
			return R.data( standard );
		} else {
			return R.data( 100 );
		}
	}

	/**
	 * 根据ID获取相关信息
	 *
	 * @param id
	 * @return
	 */
	@GetMapping("/getStandardById")
	@ApiOperation(value = "根据ID获取相关信息", notes = "id")
	public R getStandardById(String id) {
		Map<String, Object> rmap = new HashMap<>();
		try {
			Welfare welfare = iWelfareService.getById( id );
			rmap.put( "welfare", welfare );
			//QueryWrapper<InvoiceImage> queryWrapper = new QueryWrapper<>();
			//queryWrapper.eq( "bx_id", String.valueOf( welfare.getId() ) );
			//List<InvoiceImage> image = imageService.list( queryWrapper );
			//rmap.put( "image", image );
		} catch (Exception e) {
			e.printStackTrace();
			return R.data( 200, rmap, "exception:" + e.getMessage() );
		}
		return R.data( rmap );
	}

	@PostMapping("/getNotUploadWelfareList")
	@ApiOperation(value = "根据ID获取相关信息", notes = "id")
	public R getNotUploadWelfareList(@RequestBody Map<String, Object> map) {
		Map<String, Object> rmap = new HashMap<>();

		String time = map.get( "time" ).toString();
		String fyType = map.get( "fyType" ).toString();
		String bmid = map.get( "bmid" ) == null ? "" : map.get( "bmid" ).toString();
		String xm = map.get( "xm" ) == null ? "" : map.get( "xm" ).toString();
		Integer page = Integer.valueOf( map.get( "page" ).toString() );
		Integer pageSize = Integer.valueOf( map.get( "pageSize" ).toString() );
		Map<String, Object> params = new HashMap<>();
		params.put( "time", time );
		params.put( "fyType", fyType );
		params.put( "bmid", bmid );
		params.put( "xm", xm );
		List<Map<String, Object>> listCount = iWelfareService.getNotUploadWelfareList( params );
		params.put( "limit", getLimitStr( pageSize, page ) );
		try {
			List<Map<String, Object>> list = iWelfareService.getNotUploadWelfareList( params );
			rmap.put( "total", listCount.size() );
			rmap.put( "data", list );
		} catch (Exception e) {
			e.printStackTrace();
			return R.data( 200, rmap, "exception:" + e.getMessage() );
		}
		return R.data( rmap );
	}

	@GetMapping("/downFileById")
	public void downFileById(HttpServletResponse response, String id, BladeUser user) {
		Welfare welfare = iWelfareService.getById( id );
		String fyType = dictClient.getValue( "bx_welfare", Integer.valueOf( welfare.getFyType() ) ).getData();
		String userName = userClient.userInfo( Long.valueOf( welfare.getCreateUser() ) ).getData().getUser().getName();
		String strDateFormat = "yyyyMM";
		SimpleDateFormat sdf = new SimpleDateFormat( strDateFormat );
		String zipName = sdf.format( welfare.getFyDate() ) + "-" + userName+ "-" + fyType ;
		InvoiceImage invoiceImage = new InvoiceImage();
		invoiceImage.setBxId( id );
		invoiceImage.setModelType("2");
		List<InvoiceImageVo> imgList = InvoiceImageWrapper.build().entityVOList( imageService.list( Wrappers.query( invoiceImage ) ) );
		String ids = "";
		for (int i = 0; i < imgList.size(); i++) {
			if (i == 0) {
				ids = imgList.get( i ).getId().toString();
			} else {
				ids = ids + "," + imgList.get( i ).getId();
			}
		}
		imageService.downloadBatch( response, ids, zipName );
	}

	@GetMapping("/downFileFLData")
	public void downFileFLData(HttpServletResponse response, String time, String fyType) {
		Map<String, Object> params = new HashMap<>();
		params.put( "time", time );
		params.put( "fyType", fyType );
		String fyTypeValue = dictClient.getValue( "bx_welfare", Integer.valueOf( fyType ) ).getData();
		List<Map<String, Object>> list = iWelfareService.getWelfareList( params );
		List<String> fies = new ArrayList<>();

		File newFile = createNewFile();
		String uploadRealPath = SystemConstant.me().getUploadRealPath();
		File tempDirectory = new File( uploadRealPath + "/福利费文件" );
		fies.add( tempDirectory.getPath() );
		//新文件写入数据，并下载*****************************************************
		InputStream is = null;
		XSSFWorkbook xSSFWorkbook = null;
		XSSFSheet xSSFSheet = null;
		OutputStream out = null;
		try {
			response.setContentType( "application/zip" );
			String newName = URLEncoder.encode( time + "福利费" + System.currentTimeMillis() + ".zip", "UTF-8" );
			response.addHeader( "Content-Disposition", "attachment;filename=\"" + newName + "\"" );
			out = response.getOutputStream();
			is = new FileInputStream( newFile );
			xSSFWorkbook = new XSSFWorkbook( is );
			//获取第一个sheet
			xSSFSheet = xSSFWorkbook.getSheetAt( 0 );
		} catch (Exception e1) {
			e1.printStackTrace();
		}
		XSSFFont centerfont = xSSFWorkbook.createFont();
		centerfont.setFontName( "宋体" );
		centerfont.setFontHeightInPoints( (short) 12 );
		XSSFCellStyle centerstyle = xSSFWorkbook.createCellStyle();
		centerstyle.setFont( centerfont );
		centerstyle.setAlignment( HorizontalAlignment.CENTER );//水平居中
		centerstyle.setVerticalAlignment( VerticalAlignment.CENTER );//垂直居中
		centerstyle.setWrapText( true );
		if (xSSFSheet != null) {
			try {
				//写数据
				FileOutputStream fos = new FileOutputStream( newFile );
				//输出行数据
				Row row0 = xSSFSheet.createRow( 0 );
				Cell cell0;
				cell0 = row0.createCell( 0 );
				cell0.setCellValue( time + fyTypeValue );
				cell0.setCellStyle( centerstyle );
				//构建每行的数据内容
				int rowNum = 2;
				int xh = 1;
				for (Map<String, Object> data : list) {
					if (data == null) {
						continue;
					}
					InvoiceImage invoiceImage = new InvoiceImage();
					invoiceImage.setBxId( data.get( "id" ).toString() );
					invoiceImage.setModelType("2");
					List<InvoiceImageVo> imgList = InvoiceImageWrapper.build().entityVOList( imageService.list( Wrappers.query( invoiceImage ) ) );
					List<String> pathList = new ArrayList<>();
					for (InvoiceImageVo invoiceImageVo : imgList) {
						pathList.add( invoiceImageVo.getPath() );
					}

					if (!tempDirectory.exists()) {
						tempDirectory.mkdirs();
					}
					for (int i = 0; i < pathList.size(); i++) {
						String newFileName = "";
						String hzm = pathList.get( i ).substring( pathList.get( i ).lastIndexOf( "." ));//后缀名
						if(pathList.size()>1){
							newFileName = tempDirectory + File.separator + data.get( "fy_date" ).toString() + data.get( "xm" ).toString()
								+ data.get( "flflx" ).toString() + (i+1) +hzm ;
						}else{
							newFileName = tempDirectory + File.separator + data.get( "fy_date" ).toString() + data.get( "xm" ).toString()
								+ data.get( "flflx" ).toString() +hzm;
						}
						ImageUtil.fileCopyRightWay( pathList.get( i ), newFileName );
					}
					//输出行数据
					Row row = xSSFSheet.createRow( rowNum++ );
					int cellNum = 0;
					Cell cell;
					// 序号
					cell = row.createCell( cellNum++ );
					cell.setCellValue( xh );
					cell.setCellStyle( centerstyle );
					// 一级科
					cell = row.createCell( cellNum++ );
					cell.setCellValue( "管理费用" );
					cell.setCellStyle( centerstyle );
					// 二级科
					cell = row.createCell( cellNum++ );
					cell.setCellValue( "福利费" );
					cell.setCellStyle( centerstyle );
					// 摘要
					cell = row.createCell( cellNum++ );
					cell.setCellValue( data.get( "fy_date" ).toString() + data.get( "flflx" ).toString() );
					cell.setCellStyle( centerstyle );
					// 姓名
					cell = row.createCell( cellNum++ );
					cell.setCellValue( data.get( "xm" ).toString() );
					cell.setCellStyle( centerstyle );
					// 标准
					cell = row.createCell( cellNum++ );
					cell.setCellValue( data.get( "fyStandard" ).toString() );
					cell.setCellStyle( centerstyle );
					// 报销金额
					cell = row.createCell( cellNum++ );
					cell.setCellValue( data.get( "bcAmount" ).toString() );
					cell.setCellStyle( centerstyle );
					// 发票金额
					cell = row.createCell( cellNum++ );
					cell.setCellValue( data.get( "fpAmount" ).toString() );
					cell.setCellStyle( centerstyle );

					xh++;
				}
				xSSFWorkbook.write( fos );
				fos.flush();
				fos.close();

				fies.add( newFile.getPath() );

			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				try {
					if (null != is) {
						is.close();
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
		try {
			ZipUtils.toAllZip( fies.toArray( new String[fies.size()] ), out, true );
		} catch (Exception e) {
			e.printStackTrace();
		}
		//下载成功后删除临时文件和文件夹
		ImageUtil.deleteFile( tempDirectory );
		ImageUtil.deleteFile( newFile );
	}

	/**
	 * 根据 页码、页大小 获取分页字符串 " LIMIT 1,10 "
	 */
	public static String getLimitStr(Integer size, Integer page) {
		String str = "";
		try {
			Integer num = (page - 1) * size;
			str = " LIMIT " + num + "," + size + "";
		} catch (Exception e) {
			e.printStackTrace();
		}
		return str;
	}

	/**
	 * 复制文件
	 *
	 * @param in 源文件
	 * @param t 复制到的新文件
	 */
	public void fileChannelCopy(InputStream in, File t) {
		try {
			//InputStream in = null;
			OutputStream out = null;
			try {
				//in = new BufferedInputStream( new FileInputStream( s ), 1024 );
				out = new BufferedOutputStream( new FileOutputStream( t ), 1024 );
				byte[] buffer = new byte[1024];
				int len;
				while ((len = in.read( buffer )) != -1) {
					out.write( buffer, 0, len );
				}
			} finally {
				if (null != in) {
					in.close();
				}
				if (null != out) {
					out.close();
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 读取excel模板，并复制到新文件中供写入和下载
	 *
	 * @return
	 */
	public File createNewFile() {
		//构建成jar运行 非文本文件读取
		ClassPathResource classPathResource = new ClassPathResource("template/welfareTemplate.xlsx");
		InputStream inputStream = null;
		try {
			inputStream = classPathResource.getInputStream();
		} catch (IOException e) {
			e.printStackTrace();
		}
		//读取模板，并赋值到新文件************************************************************
		//文件模板路径
		//String path = this.getRequest().getRealPath( SystemConfig.FILETEMPLATE );
		//String fileName = "welfareTemplate.xlsx";
		//File file = new File( path );

		//保存文件的路径
		//创建临时文件夹
		String uploadRealPath = SystemConstant.me().getUploadRealPath();
		//新的文件名
		String newFileName = "福利费统计" + System.currentTimeMillis() + ".xlsx";
		//判断路径是否存在
		File dir = new File( uploadRealPath );
		if (!dir.exists()) {
			dir.mkdirs();
		}
		//写入到新的excel
		File newFile = new File( uploadRealPath, newFileName );
		try {
			newFile.createNewFile();
			//复制模板到新文件
			fileChannelCopy( inputStream, newFile );
		} catch (Exception e) {
			e.printStackTrace();
		}
		return newFile;
	}
}
